<template>
  <div class="role-manage">
      <div class="page-header">
        <h2>角色管理</h2>
        <div class="header-actions">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            添加角色
          </el-button>
        </div>
      </div>

      <!-- 搜索筛选区域 -->
      <div class="filter-container">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="角色名称">
            <el-input v-model="searchForm.name" placeholder="请输入角色名称" clearable />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
              <el-option label="启用" value="active" />
              <el-option label="禁用" value="inactive" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 表格区域 -->
      <div class="table-container">
        <el-table
          :data="tableData"
          border
          stripe
          style="width: 100%"
          v-loading="loading"
        >
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="name" label="角色名称" width="150" />
          <el-table-column prop="description" label="描述" min-width="200" />
          <el-table-column prop="userCount" label="用户数量" width="100" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.status === 'active' ? 'success' : 'danger'">
                {{ scope.row.status === 'active' ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="180" />
          <el-table-column label="操作" width="220" fixed="right">
            <template #default="scope">
              <el-button type="primary" size="small" @click="handleEdit(scope.row)">
                <el-icon><Edit /></el-icon>
                编辑
              </el-button>
              <el-button type="info" size="small" @click="handlePermission(scope.row)">
                <el-icon><Key /></el-icon>
                权限
              </el-button>
              <el-button type="danger" size="small" @click="handleDelete(scope.row)">
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>

      <!-- 添加/编辑对话框 -->
      <el-dialog
        v-model="dialogVisible"
        :title="dialogType === 'add' ? '添加角色' : '编辑角色'"
        width="600px"
        @close="handleDialogClose"
      >
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="80px"
          style="padding-right: 20px"
        >
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="form.name" />
          </el-form-item>
          <el-form-item label="描述" prop="description">
            <el-input v-model="form.description" type="textarea" :rows="3" />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio label="active">启用</el-radio>
              <el-radio label="inactive">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSubmit">确定</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 权限设置对话框 -->
      <el-dialog
        v-model="permissionDialogVisible"
        title="权限设置"
        width="800px"
        @close="handlePermissionDialogClose"
      >
        <div class="permission-content">
          <div class="role-info">
            <span>角色名称: </span>
            <span class="role-name">{{ currentRole.name }}</span>
          </div>
          
          <el-divider />
          
          <div class="permission-tree">
            <el-tree
              ref="permissionTreeRef"
              :data="permissionData"
              :props="defaultProps"
              show-checkbox
              node-key="id"
              :default-expanded-keys="[1, 2, 3, 4, 5]"
              :default-checked-keys="checkedPermissions"
            />
          </div>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="permissionDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handlePermissionSubmit">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  Plus,
  Delete,
  Edit,
  Search,
  Refresh,
  Key
} from '@element-plus/icons-vue';

// 表格数据
const tableData = ref([]);
const loading = ref(false);

// 搜索表单
const searchForm = reactive({
  name: '',
  status: ''
});

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 对话框
const dialogVisible = ref(false);
const dialogType = ref('add'); // 'add' 或 'edit'
const formRef = ref(null);

// 表单数据
const form = reactive({
  id: '',
  name: '',
  description: '',
  status: 'active'
});

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 20, message: '角色名称长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入角色描述', trigger: 'blur' },
    { min: 5, max: 100, message: '描述长度在 5 到 100 个字符', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
};

// 权限对话框
const permissionDialogVisible = ref(false);
const permissionTreeRef = ref(null);
const currentRole = ref({});
const checkedPermissions = ref([]);

// 权限数据
const permissionData = [
  {
    id: 1,
    label: '系统管理',
    children: [
      {
        id: 11,
        label: '用户管理',
        children: [
          { id: 111, label: '查看用户' },
          { id: 112, label: '添加用户' },
          { id: 113, label: '编辑用户' },
          { id: 114, label: '删除用户' }
        ]
      },
      {
        id: 12,
        label: '角色管理',
        children: [
          { id: 121, label: '查看角色' },
          { id: 122, label: '添加角色' },
          { id: 123, label: '编辑角色' },
          { id: 124, label: '删除角色' },
          { id: 125, label: '分配权限' }
        ]
      }
    ]
  },
  {
    id: 2,
    label: '学生管理',
    children: [
      {
        id: 21,
        label: '学生信息',
        children: [
          { id: 211, label: '查看学生' },
          { id: 212, label: '添加学生' },
          { id: 213, label: '编辑学生' },
          { id: 214, label: '删除学生' }
        ]
      },
      {
        id: 22,
        label: '班级管理',
        children: [
          { id: 221, label: '查看班级' },
          { id: 222, label: '添加班级' },
          { id: 223, label: '编辑班级' },
          { id: 224, label: '删除班级' }
        ]
      }
    ]
  },
  {
    id: 3,
    label: '教师管理',
    children: [
      {
        id: 31,
        label: '教师信息',
        children: [
          { id: 311, label: '查看教师' },
          { id: 312, label: '添加教师' },
          { id: 313, label: '编辑教师' },
          { id: 314, label: '删除教师' }
        ]
      }
    ]
  },
  {
    id: 4,
    label: '课程管理',
    children: [
      {
        id: 41,
        label: '课程信息',
        children: [
          { id: 411, label: '查看课程' },
          { id: 412, label: '添加课程' },
          { id: 413, label: '编辑课程' },
          { id: 414, label: '删除课程' }
        ]
      }
    ]
  },
  {
    id: 5,
    label: '成绩管理',
    children: [
      {
        id: 51,
        label: '成绩信息',
        children: [
          { id: 511, label: '查看成绩' },
          { id: 512, label: '录入成绩' },
          { id: 513, label: '编辑成绩' },
          { id: 514, label: '删除成绩' }
        ]
      }
    ]
  }
];

const defaultProps = {
  children: 'children',
  label: 'label'
};

// 获取角色列表
const getRoleList = async () => {
  loading.value = true;
  try {
    const response = await roleApi.getRoleList({
      page: pagination.currentPage,
      size: pagination.pageSize,
      ...searchForm
    });
    
    if (response.code === 200) {
      tableData.value = response.data.list || [];
      pagination.total = response.data.total || 0;
    } else {
      console.error('获取角色列表失败:', response.message);
      ElMessage.error('获取角色列表失败');
      tableData.value = [];
      pagination.total = 0;
    }
  } catch (error) {
    console.error('获取角色列表失败:', error);
    ElMessage.error('获取角色列表失败');
    tableData.value = [];
    pagination.total = 0;
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1;
  getRoleList();
};

// 重置
const handleReset = () => {
  searchForm.name = '';
  searchForm.status = '';
  handleSearch();
};

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.pageSize = size;
  getRoleList();
};

// 当前页变化
const handleCurrentChange = (page) => {
  pagination.currentPage = page;
  getRoleList();
};

// 添加角色
const handleAdd = () => {
  dialogType.value = 'add';
  dialogVisible.value = true;
  // 重置表单
  form.id = '';
  form.name = '';
  form.description = '';
  form.status = 'active';
};

// 编辑角色
const handleEdit = (row) => {
  dialogType.value = 'edit';
  dialogVisible.value = true;
  // 填充表单
  form.id = row.id;
  form.name = row.name;
  form.description = row.description;
  form.status = row.status;
};

// 删除角色
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除角色 ${row.name} 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      // 这里应该是实际的API调用
      ElMessage.success('删除成功');
      getRoleList();
    })
    .catch(() => {
      // 取消删除
    });
};

// 权限设置
const handlePermission = async (row) => {
  currentRole.value = row;
  
  try {
    // 获取角色权限
    const response = await roleApi.getRolePermissions(row.id);
    
    if (response.code === 200) {
      checkedPermissions.value = response.data || [];
    } else {
      console.error('获取角色权限失败:', response.message);
      ElMessage.error('获取角色权限失败');
      checkedPermissions.value = [];
    }
  } catch (error) {
    console.error('获取角色权限失败:', error);
    ElMessage.error('获取角色权限失败');
    checkedPermissions.value = [];
  }
  
  permissionDialogVisible.value = true;
};

// 提交表单
const handleSubmit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      // 这里应该是实际的API调用
      ElMessage.success(dialogType.value === 'add' ? '添加成功' : '修改成功');
      dialogVisible.value = false;
      getRoleList();
    }
  });
};

// 提交权限设置
const handlePermissionSubmit = () => {
  const checkedKeys = permissionTreeRef.value.getCheckedKeys();
  const halfCheckedKeys = permissionTreeRef.value.getHalfCheckedKeys();
  const allCheckedKeys = [...checkedKeys, ...halfCheckedKeys];
  
  // 这里应该是实际的API调用
  ElMessage.success('权限设置成功');
  permissionDialogVisible.value = false;
};

// 对话框关闭
const handleDialogClose = () => {
  formRef.value?.resetFields();
};

// 权限对话框关闭
const handlePermissionDialogClose = () => {
  // 清空选中的权限
  checkedPermissions.value = [];
};

// 初始化
onMounted(() => {
  getRoleList();
});
</script>

<style scoped>
.role-manage {
  padding: 20px;
  background-color: #f0f2f5;
  min-height: calc(100vh - 60px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 0 5px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.filter-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-form {
  margin: 0;
}

.table-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.permission-content {
  max-height: 500px;
  overflow-y: auto;
}

.role-info {
  font-size: 16px;
  margin-bottom: 15px;
}

.role-name {
  font-weight: bold;
  color: #409EFF;
}

.permission-tree {
  margin-top: 15px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .role-manage {
    padding: 10px;
  }
  
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .header-actions {
    width: 100%;
    justify-content: flex-start;
  }
  
  .search-form {
    display: flex;
    flex-direction: column;
    gap: 10px;
  }
  
  .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
  }
}
</style>